package com.comdosoft.comdoandroidbase.fragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.comdosoft.comdoandroidbase.MyApplication;
import com.comdosoft.comdoandroidbase.R;
import com.comdosoft.comdoandroidbase.util.CommonUtils;
import com.comdosoft.comdoandroidbase.util.ImageUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;

/**
 * 常用图片处理合集
 *
 * @author niemin
 */

public class ImageFragment extends Fragment implements View.OnClickListener {
    private View view;
    private TextView singleImage;               //单张图片拍照、选择图片，图片压缩
    private TextView ImageLoaderButton;
    private ImageView chooseImageView, ImageLoaderView;

    private Dialog noticeDialog = null;

    DisplayImageOptions options = MyApplication.getDisplayDefaultOption();
    private boolean isShowImageLoaderView = true;
    // 头像
    private File picture;
    // 头像地址
    private String imgaePath;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_image, container, false);
        initView();
        return view;
    }

    private void initView() {
        singleImage = (TextView) view.findViewById(R.id.singleImage);
        ImageLoaderButton = (TextView) view.findViewById(R.id.ImageLoaderButton);
        chooseImageView = (ImageView) view.findViewById(R.id.chooseImageView);
        ImageLoaderView = (ImageView) view.findViewById(R.id.ImageLoaderView);

        singleImage.setOnClickListener(this);
        ImageLoaderButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.singleImage:
                showChooseDialog();
                break;
            case R.id.ImageLoaderButton:
                if (isShowImageLoaderView == true) {
                    isShowImageLoaderView = false;

                    String url = "http://pica.nipic.com/2007-11-09/2007119124513598_2.jpg";
                    System.out.println("url==" + url);
                    ImageLoader.getInstance().displayImage(url, ImageLoaderView, options);
                    ImageLoaderView.setVisibility(View.VISIBLE);
                } else {
                    isShowImageLoaderView = true;
                    ImageLoaderView.setVisibility(View.GONE);
                }
                break;
            default:
                break;
        }
    }

    private void showChooseDialog() {

        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater factory = LayoutInflater.from(getActivity());
        final View textEntryView = factory.inflate(R.layout.choose_dialog, null);
        // builder.setTitle("自定义输入框");
        builder.setView(textEntryView);
        final Button choosealbum = (Button) textEntryView
                .findViewById(R.id.choosealbum);
        final Button choosecamera = (Button) textEntryView
                .findViewById(R.id.choosecamera);
        noticeDialog = builder.create();
        choosealbum.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                noticeDialog.dismiss();
                openAlbum();
            }
        });
        choosecamera.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                noticeDialog.dismiss();
                opencamera();
            }
        });
        noticeDialog.show();

    }

    protected void openAlbum() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, 1002);

    }

    protected void opencamera() {

        // 激活相机
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        // 判断存储卡是否可以用，可用进行存储
        if (CommonUtils.hasSDCard() == true) {
            String name = "/userPicture"
                    + Calendar.getInstance().getTimeInMillis() + ".jpg";
            imgaePath = Environment.getExternalStorageDirectory() + name;
            picture = new File(Environment.getExternalStorageDirectory(), name);

            // 从文件中创建uri
            Uri uri = Uri.fromFile(picture);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
        startActivityForResult(intent, 1001);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1001:

                if (picture.exists()) {
                /*
                 * BitmapFactory.decodeFile(String path, Options opt)
				 * 并不会真的返回一个Bitmap给你，它仅仅会把它的宽，高取回来给你
				 * 避免OOM
				 * 这里返回的bmp是null
				 * */
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    Bitmap bmp = BitmapFactory.decodeFile(imgaePath, options);
                    int pictureWidth = options.outWidth;
                    int pictureHeight = options.outHeight;
                /*
                 * 图片压缩处理
				 * 1）将拍完的照片先将尺寸压缩到原来的75%；
				 * 2）再将第1）步完成后的图片质量降到原来的75（质量是1到100的值）。
				 */
                    try {
                        //1）将拍完的照片先将尺寸压缩到原来的75%；
                        Bitmap bitmap = ImageUtil.ratio(imgaePath, (float) (pictureWidth * 0.75), (float) (pictureHeight * 0.75));

                        bitmap = ImageUtil.rotateBitmap(bitmap,
                                ImageUtil.readPictureDegree(imgaePath));
                        //2）再将第1）步完成后的图片质量降到原来的75（质量是1到100的值）
                        ImageUtil.compressAndGenImage(bitmap, picture.getPath());
                        bitmap.recycle();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    showImage(imgaePath);

                    //      updataAvatar(picture);
                }

                break;
            case 1002:

                if (data == null) {
                    return;
                }

                Uri uri = data.getData();
                String[] proj = {MediaStore.Images.Media.DATA};
                Cursor actualimagecursor = getActivity().getContentResolver().query(uri, proj, null, null, null);
			/*
			 * 兼容性
			 * 本地图片返回格式1）content://media/external/images/media/244709
			 * 本地图片返回格式2）/storage/sdcard0/DCIM/Camera/IMG_20140608_162447.jpg
			 * 需要分别处理
			 */
                if (actualimagecursor != null) {
                    if (actualimagecursor.moveToFirst()) {
                        int columnIndex = actualimagecursor.getColumnIndexOrThrow(proj[0]);
                        imgaePath = actualimagecursor.getString(columnIndex);
                    }
                    actualimagecursor.close();
                } else {
                    if (uri != null) {
                        String tmpPath = uri.getPath();
                        if (tmpPath != null && (tmpPath.endsWith(".jpg") || tmpPath.endsWith(".png") || tmpPath.endsWith(".gif"))) {
                            imgaePath = tmpPath;
                        }
                    }
                }

                if (CommonUtils.hasSDCard() == true) {
                    String tempPath = Environment.getExternalStorageDirectory()
                            + "/userPicture.jpg";

				/*
				 * BitmapFactory.decodeFile(String path, Options opt)
				 * 并不会真的返回一个Bitmap给你，它仅仅会把它的宽，高取回来给你
				 * 避免OOM
				 * 这里返回的bmp是null
				 * */
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    Bitmap bmp = BitmapFactory.decodeFile(imgaePath, options);
                    int pictureWidth = options.outWidth;
                    int pictureHeight = options.outHeight;
				/*
				 * 图片压缩处理
				 * 1）将拍完的照片先将尺寸压缩到原来的75%；
				 * 2）再将第1）步完成后的图片质量降到原来的75（质量是1到100的值）。
				 */
                    try {
                        //1）将拍完的照片先将尺寸压缩到原来的75%；
                        Bitmap bitmap = ImageUtil.ratio(imgaePath, (float) (pictureWidth * 0.75), (float) (pictureHeight * 0.75));
                        //2）再将第1）步完成后的图片质量降到原来的75（质量是1到100的值）
                        ImageUtil.compressAndGenImage(bitmap, tempPath);
                        bitmap.recycle();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    picture = new File(tempPath);
                    showImage(tempPath);
                    //		updataAvatar(picture);
                } else {
                    picture = new File(imgaePath);
                    showImage(imgaePath);
                    //		updataAvatar(picture);
                }

                break;
            default:
                break;
        }
    }

    private void showImage(String picturePath) {
        chooseImageView.setVisibility(View.VISIBLE);
        Bitmap bm = BitmapFactory.decodeByteArray(
                ImageUtil.decodeBitmap(picturePath), 0,
                ImageUtil.decodeBitmap(picturePath).length);
        chooseImageView.setImageBitmap(bm);
    }
}
